<style lang="less">
@import "../../styles/common.less";
.ivu-table .table-info-normal td {
  background-color: #2db7f5;
}

.ivu-table .table-info-live td {
  background-color: #e2fcde;
}

.ivu-table .table-info-not-live td {
  background-color: #fee6d4;
}
.ivu-table .table-info-error td {
  background-color: #ffe3e3;
}

.ivu-table .table-info-shrink td {
  background-color: lightgray;
  // margin-left: 10;
}
</style>

<template>
  <div class="margin-top-10">
    <Row type="flex" justify="space-between">
      <Row>
        <Input
          v-model.trim="queryForm.group_name"
          @on-enter="searchRecord"
          placeholder="请输入集团名称"
          style="width:150px;margin-right:8px"
        ></Input>
        <Input
          v-model.trim="queryForm.campus_name"
          @on-enter="searchRecord"
          placeholder="请输入校区名称"
          style="width:150px;margin-right:8px"
        ></Input>
        <Input
          v-model.trim="queryForm.class_name"
          @on-enter="searchRecord"
          placeholder="请输入班级名称"
          style="width:150px;margin-right:8px"
        ></Input>
        <DatePicker
          type="datetimerange"
          v-model="queryDateRange"
          placeholder="选择时间段"
          format="yyyy-MM-dd HH:mm"
          style="width: 300px;margin-right:8px"
        ></DatePicker>
        <Button @click="searchRecord" type="primary">查询</Button>
      </Row>
      <Row style="display: none">
        <Button>导出</Button>
      </Row>
    </Row>
    <div class="margin-top-10">
      <Table
        :row-class-name="rowClassName"
        :columns="recColumn"
        :data="tabelData"
        :loading="tableLoading"
        ref="recTable"
      ></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="recHistory.total"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="pageQuery"
        show-total
      >总数为{{recHistory.total}}条</Page>
    </Row>
    <!-- <AddGuestModal ref="addGuestModal" @updated="updated"/>
    <AddStaffModal ref="addStaffModal" @updated="updated"/>
    <AddVIPModal ref="addVIPModal" @updated="updated"/>
    <AddStudentModal ref="addStudentModal" @updated="updated"/>
    <MergeToModal ref="mergeToModal" @updated="updated"/> -->
  </div>
</template>

<script>
import {
  getHistoryData,
  getAvatar,
  getTypeList,
  getDownloadUrl
} from "../../controllers/record";
// import {
//   //
// }

import Ajax from "../../libs/ajax";
import Constant from "../../libs/constants";
import _ from "lodash";
import fakeAvatar from "../../images/default_avatar.png";
import DateUtils from "../../../node_modules/iview/src/utils/date";
import moment from "moment";
import AddGuestModal from "./components/AddGuestModal";
import AddStaffModal from "./components/AddStaffModal";
import AddVIPModal from "./components/AddVIPModal";
import AddStudentModal from "./components/AddStudentModal";

import MergeToModal from "./components/MergeToModal";
import Util from "../../libs/util";

export default {
  components: {
    AddGuestModal,
    AddStaffModal,
    AddVIPModal,
    AddStudentModal,
    MergeToModal
  },
  data() {
    // 默认检索3天
    const from = moment()
      .subtract(2, "days")
      .format("YYYYMMDD");
    const to = moment().format("YYYYMMDD") + "2359";
    return {
      tableLoading: true,
      queryDateRange: [
        DateUtils.parse(from, "yyyyMMdd"),
        DateUtils.parse(to, "yyyyMMddHHmm")
      ],
      queryForm:{
        group_name:'',
        campus_name:'',
        class_name:'',
      },
      tabelData:[],
      recColumn: [
        {
          title: "抓拍照片",
          key: "rec_capture",
          align: "center",
          width:200,
          render: (h, { row, column, index }) => {
            //拼装url
            let imgSrc = row.c_photo_path?row.c_photo_path:row.rec_capture;      
            return (
              <div>
                <img class="user-avatar" alt="抓拍照片" src={imgSrc} />
              </div>
            );
          }
        },
        {
          title: "集团名称",
          key: "group_name",
          align: "center",
          width:200,
        },
        {
          title: "校区ID",
          key: "campus_id",
          align: "center",
          width:200,
        },
        {
          title: "教室ID",
          key: "classroom_id",
          align: "center",
          width:200,
        },
        {
          title: "摄像头ID",
          key: "ipc_id",
          align: "center",
          width:200,
        },
        // {
        //   title: "摄像头名字",
        //   key: "ipc_name",
        //   align: "center",
        //   width:200,
        // },
        {
          title: "抓拍时间",
          key: "rec_time",
          align: "center",
          width:200,
        },
        {
          title: "抓拍下载",
          align: "center",
          width:200,
          render: (h, { row }) => {
            let id = row.rec_id;
            let type = "register";
            let userId = row.user_id;
            if (!userId) type = "stranger";
            return h(
              "a",
              {
                attrs: {
                  // href:`/api/record/download_capture?rec_id=${id}&type=${type}`,
                },
                on: {
                  click: () => {
                    if(row.d_uuid){
                      // 巨龙设备保存图片
                      Util.saveImg(row.c_photo_path)
                      return
                    }
                    getDownloadUrl(id, type).then(json => {
                      window.json = json;
                      if (json.code == 0) {
                        let path = json.data.path;
                        let name = json.data.name;
                        let dir = json.data.dir;
                        this.downloadByIframe(dir, path, name);
                      }
                    });
                  }
                }
              },
              "抓拍下载"
            );
          }
        },
        {
          title: "身份操作",
          align: "center",
          width: 200,
          render: (h, { row }) => {
            
            // 巨龙设备
            return h("div",[
              h(
              "Dropdown",
              {
                props: {
                  trigger: "click"
                },
                on: {
                  "on-click": value => {
                    console.log(value); //此处的value和下面DropdownMenu选项的name对应
                    this.handleOption(value, row);
                  }
                }
              },
              [
                h("Button", {}, [
                  h("span", "标记为 "), //span中的内容
                  h("Icon", {
                    props: {
                      type: "arrow-down-b"
                    }
                  })
                ]),
                h(
                  "DropdownMenu",
                  {
                    slot: "list"
                  },
                  [
                    h(
                      "DropdownItem",
                      {
                        props: {
                          name: "student"
                        }
                      },
                      "新建学生"
                    ),
                  ]
                )
              ]
            )
            ])
            
            // return h("div", [
            //   h(
            //     "Dropdown",
            //     {
            //       props: {
            //         trigger: "click"
            //       },
            //       on: {
            //         "on-click": value => {
            //           console.log(value); //此处的value和下面DropdownMenu选项的name对应
            //           this.handleOption(value, row);
            //         }
            //       }
            //     },
            //     [
            //       h("Button", {}, [
            //         h("span", "标记为 "), //span中的内容
            //         h("Icon", {
            //           props: {
            //             type: "arrow-down-b"
            //           }
            //         })
            //       ]),
            //       h(
            //         "DropdownMenu",
            //         {
            //           slot: "list"
            //         },
            //         [
            //           h(
            //             "DropdownItem",
            //             {
            //               props: {
            //                 name: "staff"
            //               }
            //             },
            //             "新建员工"
            //           ),
            //           h(
            //             "DropdownItem",
            //             {
            //               props: {
            //                 name: "vip"
            //               }
            //             },
            //             "新建 VIP"
            //           ),
            //           h(
            //             "DropdownItem",
            //             {
            //               props: {
            //                 name: "guest"
            //               }
            //             },
            //             "新建访客"
            //           ),
            //           h(
            //             "DropdownItem",
            //             {
            //               props: {
            //                 name: "merge"
            //               }
            //             },
            //             "合并至已有人员"
            //           )
            //         ]
            //       )
            //     ]
            //   )
            // ]);
          }
        }
      ],
      currentPage: 1,
      pageSize: Constant.PAGE_SIZE,
      totalVisitHistory: 0,
      recHistory: {
        data: { total: 0, result: {} }, // 一次检索的所有数据
        total: 0,
        page: {}
      },
      typeList: [],
      queryUserType: "4"
    };
  },
  created() {
    this.getRec();
    // this.initTypeList();
  },
  methods: {
    rowClassName(row, index) {
      let cls = "";
      // if (row.isExpand) {
      //   cls = "table-info-shrink ";
      // }
      if (row.liveness == "0") {
        cls += "table-info-not-live";
      } else if (row.liveness == "1") {
        cls += "table-info-live";
      } else if (row.liveness == "-2") {
        cls += "table-info-error";
      }
      return cls;
    },
    getRec(page) {
      //获取分页参数，请求后端数据
      this.tableLoading = true;
      let dateFrom = "";
      let dateTo = "";
      if (
        this.queryDateRange.length > 1 &&
        this.queryDateRange[0] != null &&
        this.queryDateRange[1] != null
      ) {
        dateFrom = DateUtils.format(this.queryDateRange[0], "yyyyMMddHHmmss");
        dateTo = DateUtils.format(this.queryDateRange[1], "yyyyMMddHHmmss");
      }
      getHistoryData(
          this.currentPage,
          this.pageSize,
          "stranger",
          "",
          "",
          dateFrom,
          dateTo,
          this.queryForm.group_name,
          this.queryForm.campus_name,
          this.queryForm.class_name,
        ).then(json => {
        this.tableLoading = false;
        //检测状态码
        if (json.code !== 0 ) {
          //非正常就返回空表
          return;
        }
        let data = json.data;
        //检测数据块存在及长度
        if (data === undefined) {
          return;
        }
        this.tabelData = data.result||[];
        this.recHistory.total = data.total;
      });
    },
    expandRow(params) {
      //判断当前行是否展开，如果未展开，执行以下方法，先展开再请求接口加载到tabledata中当前data index 后
      //this.recHistory.page
      console.log(params);

      if (!params.row.isDown) {
        this.recHistory.page[params.index].isDown = true;
        let newArrayData = params.row.list;
        newArrayData.map(item => {
          item.isExpand = true;
          item.upLevelIndex = params.index;
        });
        newArrayData.map((value, key) => {
          this.recHistory.page.splice(params.index + key + 1, 0, value);
        });
        // });
      } else {
        //如果当前行已展开，则隐藏
        this.recHistory.page[params.index].isDown = false;
        this.recHistory.page.splice(params.index + 1, params.row.list.length);
      }
    },
    pageQuery(page) {
      this.currentPage = page;
      this.getRec()
    },
    downloadByIframe(dir, path, name) {
      let url =
        Ajax.BASE_URL +
        `/api/record/download_capture?path=${path}&dir=${dir}&name=${name}`;
      var iframe = document.getElementById("myIframe");
      if (iframe) {
        iframe.src = url;
      } else {
        iframe = document.createElement("iframe");
        iframe.style.display = "none";
        iframe.src = url;
        iframe.id = "myIframe";
        document.body.appendChild(iframe);
      }
    },
    initTypeList() {
      getTypeList("1").then(json => {
        this.typeList = json.data;
      });
    },
    searchRecord() {
      if (
        this.queryDateRange.length == 0 ||
        this.queryDateRange[0] == null ||
        this.queryDateRange[1] == null
      ) {
        this.$Message.warning("请选择时间段");
        return;
      }
      this.currentPage = 1;
      this.getRec();
    },
    handleOption(type, row) {
      if (type == "staff") {
        this.$refs["addStaffModal"].showModal(row);
      } else if (type == "vip") {
        this.$refs["addVIPModal"].showModal(row);
      } else if (type == "guest") {
        this.$refs["addGuestModal"].showModal(row);
      } else if (type == "merge") {
        this.$refs["mergeToModal"].showModal(row);
      } else if (type == 'student'){
        this.$refs['addStudentModal'].showModal(row);
      }
    },
    // updated() {
    //   this.getRec();
    //   this.initTypeList();
    // }
    // addToStaff(row) {},
    // addToVIP(row) {},
    // addToGuest(row) {},
    // mergeTo(row) {}
  }
};

function transHistoryData(data) {
  let { total, result } = data;

  return {
    total: total,
    data: result
  };
}

function transAvatar(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { user_avatar: "", user_capture: "" };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined || data.length === 0) {
    return { user_avatar: "", user_capture: "" };
  }
  //提取->检验->组装
  return data;
}
</script>
